package cn.zdsoft.configuration.core;

import cn.zdsoft.configuration.core.exceptions.ConfigurationException;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * Created by wangdongdong on 2018/8/17 16:49.
 */
public class ExtensionLoader<T> {

    private ServiceLoader<T> loader;

    private ExtensionLoader() {}

    public static ExtensionLoader load(Class clazz) {
        ExtensionLoader loader = new ExtensionLoader();
        loader.loader = ServiceLoader.load(clazz);
        return loader;
    }

    public synchronized T load() throws ConfigurationException {
        T t = null;
        Iterator<T> iterator = loader.iterator();
        while(iterator.hasNext()) {
            t = iterator.next();
        }

        if (t == null) {
            throw new ConfigurationException("no client found!");
        }
        return t;
    }


}
